﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Soveryn.Commerce.API;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Pages
{
    public partial class PayPalRedirect : PageBaseClass
    {

        public String CartItems;
        public OrderProperties order;
        public String TransID;

        protected new void Page_PreInit(object sender, EventArgs e)
        {
            Website = WebsiteData.WebsiteDetail();
            GetCustomer();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {


                DataSet orderDetailsDataset = null;
                Dictionary<string, object> args = new Dictionary<string, object>();
                args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
                args.Add("CustomerCartSessionID", CustomerCartSessionID);
                args.Add("OrderID", Request.QueryString["OrderID"]);
                APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "OrderDetail", args, false, false);
                if (env.response != null)
                {
                    string response = (string)env.response;
                    orderDetailsDataset = new DataSet();
                    orderDetailsDataset.ReadXml(new StringReader((string)env.response));
                }

                DataTable orderDetailTable = orderDetailsDataset.Tables[0];
                DataTable paymentsTable = orderDetailsDataset.Tables[1];
                DataTable orderLinesTable = orderDetailsDataset.Tables[2];
                order = OrderProperties.Create(orderDetailTable.Rows[0]);

                foreach (DataRow p in paymentsTable.Rows)
                {
                    PaymentProperties payment = PaymentProperties.Create(p);
                    if (payment.SovPaymentMethodIDCode == "paypal-pp" && payment.PaymentAmountAccepted.Value == 0 && payment.IsSuccessfulTransaction.Value)
                    {
                        TransID = StringUtils.EncodeTo64(order.OrderID) + "|" + StringUtils.EncodeTo64(payment.PaymentID);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MiscUtils.ErrorLog(ex, "PayPalRedirect - WebsiteID:" + Website.WebsiteID + " OrderID:" + Request.QueryString["OrderID"]);
                throw;
            }
        }
    }
}